<template>
  <div class="contestant-works-container">
    <el-card class="works-card">
      <div slot="header" class="works-header">
        <span>我的参赛作品</span>
        <el-button 
          type="primary" 
          size="small" 
          @click="showUploadDialog" 
          :disabled="!canUpload || works.length >= maxWorks">
          上传作品
        </el-button>
      </div>
      
      <!-- Status Alerts -->
      <el-alert
        v-if="contestantStatus === 'pending'"
        title="您的参赛申请正在审核中，暂时无法上传作品"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>
      
      <el-alert
        v-if="contestantStatus === 'rejected'"
        title="您的参赛申请未通过审核，无法上传作品"
        type="error"
        :closable="false"
        show-icon>
      </el-alert>
      
      <el-alert
        v-if="contestantStatus === 'approved' && works.length >= maxWorks"
        title="您已上传最大数量的作品"
        type="info"
        :closable="false"
        show-icon>
      </el-alert>
      
      <!-- Loading State -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <!-- Works Display -->
      <div v-else-if="works.length > 0" class="works-grid">
        <el-card 
          v-for="work in works" 
          :key="work.id" 
          class="work-item"
          shadow="hover">
          <img :src="work.imageUrl" class="work-image" @click="viewWorkDetails(work)" />
          <div class="work-info">
            <h3>{{ work.title }}</h3>
            <p>{{ getCategoryName(work.category) }}</p>
            <p class="work-status">状态: {{ getStatusText(work.status) }}</p>
            <div class="work-actions">
              <el-button type="text" @click="viewWorkDetails(work)">查看</el-button>
              <el-button type="text" @click="deleteWork(work)" :disabled="work.status !== 'pending'">删除</el-button>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- Empty State -->
      <div v-else class="empty-state">
        <el-empty description="暂无参赛作品"></el-empty>
        <p v-if="canUpload">点击上方的"上传作品"按钮开始提交您的参赛作品</p>
      </div>
    </el-card>
    
    <!-- Upload Dialog -->
    <el-dialog
      title="上传参赛作品"
      :visible.sync="uploadDialogVisible"
      width="60%">
      <el-form :model="workForm" :rules="workRules" ref="workForm" label-width="100px">
        <el-form-item label="作品标题" prop="title">
          <el-input v-model="workForm.title" placeholder="请输入作品标题"></el-input>
        </el-form-item>
        
        <el-form-item label="作品类别" prop="category">
          <el-select v-model="workForm.category" placeholder="请选择作品类别">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="作品描述" prop="description">
          <el-input 
            type="textarea" 
            v-model="workForm.description" 
            placeholder="请描述您的作品"
            :rows="4">
          </el-input>
        </el-form-item>
        
        <el-form-item label="相机信息" prop="cameraInfo">
          <el-input v-model="workForm.cameraInfo" placeholder="请输入相机型号和参数"></el-input>
        </el-form-item>
        
        <el-form-item label="拍摄地点" prop="location">
          <el-input v-model="workForm.location" placeholder="请输入拍摄地点"></el-input>
        </el-form-item>
        
        <el-form-item label="作品图片" prop="image">
          <el-upload
            class="work-image-uploader"
            action="#"
            :http-request="handleImageUpload"
            :show-file-list="false"
            :before-upload="beforeImageUpload">
            <img v-if="imageUrl" :src="imageUrl" class="uploaded-image">
            <i v-else class="el-icon-plus upload-icon"></i>
          </el-upload>
          <div class="upload-tip">点击上传图片，JPG/PNG格式，不超过5MB</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitWorkForm" :loading="submitting">提交</el-button>
      </span>
    </el-dialog>
    
    <!-- View Work Details Dialog -->
    <el-dialog
      title="作品详情"
      :visible.sync="detailsDialogVisible"
      width="70%">
      <div v-if="selectedWork" class="work-details">
        <div class="work-image-container">
          <img :src="selectedWork.imageUrl" class="work-detail-image" />
        </div>
        <div class="work-detail-info">
          <h2>{{ selectedWork.title }}</h2>
          <p class="work-status">状态: {{ getStatusText(selectedWork.status) }}</p>
          <div class="detail-item">
            <span class="detail-label">类别:</span>
            <span>{{ getCategoryName(selectedWork.category) }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">描述:</span>
            <p>{{ selectedWork.description }}</p>
          </div>
          <div class="detail-item">
            <span class="detail-label">相机信息:</span>
            <span>{{ selectedWork.cameraInfo }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">拍摄地点:</span>
            <span>{{ selectedWork.location }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">提交时间:</span>
            <span>{{ formatDate(selectedWork.createdAt) }}</span>
          </div>
          <div v-if="selectedWork.reviewComment" class="detail-item">
            <span class="detail-label">评审意见:</span>
            <p>{{ selectedWork.reviewComment }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ContestantWorks',
  data() {
    return {
      loading: true,
      submitting: false,
      works: [],
      contestantInfo: null,
      contestantStatus: 'pending', // 'pending', 'approved', 'rejected'
      maxWorks: 3, // 最大上传作品数
      uploadDialogVisible: false,
      detailsDialogVisible: false,
      selectedWork: null,
      imageUrl: '',
      imageFile: null,
      workForm: {
        title: '',
        category: '',
        description: '',
        cameraInfo: '',
        location: '',
        image: null
      },
      workRules: {
        title: [
          { required: true, message: '请输入作品标题', trigger: 'blur' },
          { min: 2, max: 50, message: '标题长度在2到50个字符之间', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择作品类别', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入作品描述', trigger: 'blur' },
          { min: 10, max: 500, message: '描述长度在10到500个字符之间', trigger: 'blur' }
        ],
        cameraInfo: [
          { required: true, message: '请输入相机信息', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请输入拍摄地点', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请上传作品图片', trigger: 'change' }
        ]
      },
      categories: [
        { value: 'landscape', label: '风景' },
        { value: 'portrait', label: '人像' },
        { value: 'street', label: '街拍' },
        { value: 'wildlife', label: '野生动物' },
        { value: 'macro', label: '微距' },
        { value: 'architecture', label: '建筑' },
        { value: 'other', label: '其他' }
      ]
    }
  },
  computed: {
    canUpload() {
      return this.contestantStatus === 'approved'
    }
  },
  created() {
    this.fetchContestantInfo()
  },
  methods: {
    fetchContestantInfo() {
      // 获取参赛者信息
      this.loading = true
      this.$axios.get('/api/contestant/info')
        .then(response => {
          this.contestantInfo = response.data
          this.contestantStatus = response.data.status
          this.fetchWorks()
        })
        .catch(error => {
          console.error('获取参赛者信息失败:', error)
          this.$message.error('获取参赛者信息失败')
          this.loading = false
        })
    },
    fetchWorks() {
      // 获取参赛作品列表
      this.$axios.get('/api/contestant/works')
        .then(response => {
          this.works = response.data
          this.loading = false
        })
        .catch(error => {
          console.error('获取参赛作品失败:', error)
          this.$message.error('获取参赛作品失败')
          this.loading = false
        })
    },
    showUploadDialog() {
      this.resetWorkForm()
      this.uploadDialogVisible = true
    },
    resetWorkForm() {
      if (this.$refs.workForm) {
        this.$refs.workForm.resetFields()
      }
      this.workForm = {
        title: '',
        category: '',
        description: '',
        cameraInfo: '',
        location: '',
        image: null
      }
      this.imageUrl = ''
      this.imageFile = null
    },
    beforeImageUpload(file) {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPGOrPNG) {
        this.$message.error('只能上传JPG或PNG格式的图片!')
      }
      
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB!')
      }
      
      return isJPGOrPNG && isLt5M
    },
    handleImageUpload(options) {
      const file = options.file
      this.imageFile = file
      this.workForm.image = file
      
      // 预览图片
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.imageUrl = reader.result
      }
    },
    submitWorkForm() {
      this.$refs.workForm.validate(valid => {
        if (!valid) {
          return false
        }
        
        if (!this.imageFile) {
          this.$message.error('请上传作品图片')
          return
        }
        
        this.submitting = true
        
        // 创建FormData对象上传文件
        const formData = new FormData()
        formData.append('title', this.workForm.title)
        formData.append('category', this.workForm.category)
        formData.append('description', this.workForm.description)
        formData.append('cameraInfo', this.workForm.cameraInfo)
        formData.append('location', this.workForm.location)
        formData.append('image', this.imageFile)
        
        this.$axios.post('/api/contestant/works', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
          .then(response => {
            this.$message.success('作品上传成功')
            this.uploadDialogVisible = false
            this.fetchWorks() // 刷新作品列表
            this.submitting = false
          })
          .catch(error => {
            console.error('作品上传失败:', error)
            this.$message.error('作品上传失败: ' + (error.response?.data?.message || '未知错误'))
            this.submitting = false
          })
      })
    },
    viewWorkDetails(work) {
      this.selectedWork = work
      this.detailsDialogVisible = true
    },
    deleteWork(work) {
      this.$confirm('确定要删除该参赛作品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios.delete(`/api/contestant/works/${work.id}`)
            .then(response => {
              this.$message.success('作品删除成功')
              this.fetchWorks() // 刷新作品列表
            })
            .catch(error => {
              console.error('作品删除失败:', error)
              this.$message.error('作品删除失败: ' + (error.response?.data?.message || '未知错误'))
            })
        })
        .catch(() => {
          // 用户取消删除
        })
    },
    getCategoryName(categoryValue) {
      const category = this.categories.find(c => c.value === categoryValue)
      return category ? category.label : categoryValue
    },
    getStatusText(status) {
      const statusMap = {
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '未通过'
      }
      return statusMap[status] || status
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.contestant-works-container {
  padding: 20px;
}

.works-card {
  margin-bottom: 20px;
}

.works-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 20px 0;
}

.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.work-item {
  transition: all 0.3s;
}

.work-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.work-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  cursor: pointer;
}

.work-info {
  padding: 10px;
}

.work-info h3 {
  margin: 0 0 10px;
  font-size: 16px;
}

.work-info p {
  margin: 5px 0;
  color: #666;
}

.work-status {
  font-weight: bold;
}

.work-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.empty-state {
  text-align: center;
  padding: 30px 0;
}

.empty-state p {
  margin-top: 15px;
  color: #909399;
}

.work-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  max-width: 300px;
}

.work-image-uploader:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}

.work-details {
  display: flex;
  flex-wrap: wrap;
}

.work-image-container {
  flex: 0 0 50%;
  max-width: 50%;
}

.work-detail-image {
  width: 100%;
  object-fit: contain;
  max-height: 400px;
}

.work-detail-info {
  flex: 0 0 50%;
  max-width: 50%;
  padding: 0 20px;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-label {
  font-weight: bold;
  margin-right: 5px;
}

@media (max-width: 768px) {
  .work-image-container,
  .work-detail-info {
    flex: 0 0 100%;
    max-width: 100%;
  }
  
  .work-detail-info {
    padding: 20px 0 0;
  }
}
</style> 